<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>参数列表列表</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 卡片视图 -->
		<el-card>
			<el-alert title="注意,警告提示的文案" type="warning" :closable="false" show-icon>
			</el-alert>

			<!-- 选择商品分类区域 -->
			<el-row class="cat_opt">
				<el-col>
					<span>选择商品分类：</span>
					<!-- 级联选择框 -->
					<el-cascader expand-trigger="hover" v-model="value" :options="cateList" :props="cateProps" @change="handleChange"
					 ></el-cascader>
					 
					<!--  <el-cascader
								    v-model="value"
								    :options="cateList"
								    :props="[{ expandTrigger: 'hover'},{checkStrictly: true}]," 
								    @change="handleChange"></el-cascader> -->
				</el-col>
			</el-row>
			<!-- 页签 -->
			<el-tabs v-model="activeName" @tab-click="handleClick">
				<!-- 动态参数模板 -->
				<el-tab-pane label="动态参数" name="many">
					<el-button type="primary" size="mini" :disabled="isBtn" @click="adDialogVisible=true">添加参数</el-button>
					<!-- 动态参数表格 -->
					<el-table :data="manyList" border stripe>
						<!-- 展开行 -->
						<el-table-column type="expand">

							<template slot-scope="scope">
								<!-- 循环渲染tag标签 -->
								<el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
								<!-- 输入的文本框 -->
								<el-input class="input-new-tag" 
								v-if="scope.row.inputVisible" 
								v-model="scope.row.inputValue" 
								ref="saveTagInput" size="small"
								@keyup.enter.native="handleInputConfirm(scope.row)" 
								@blur="handleInputConfirm(scope.row)">
								</el-input>
								<!-- <span>{{scope.row}}</span> -->
								<!-- 添加按钮 -->
								<el-button v-else class="button-new-tag" 
								size="small" @click="showInput(scope.row)">+ New Tag</el-button>
								<pre>
									{{scope.row}}
								</pre>
							</template>
						</el-table-column>
						<el-table-column type="index"></el-table-column>
						<el-table-column label="参数名称" prop="attr_name"></el-table-column>
						<el-table-column label="操作">
							<template v-slot="scope">
								<el-button type="success" icon="el-icon-edit" size="mini" @click="showClick(scope.row.attr_id)">编辑</el-button>
								<el-button type="info" icon="el-icon-delete" size="mini" @click="removeBtn(scope.row.attr_id)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<!-- 静态参数模板 -->
				<el-tab-pane label="静态属性" name="only">
					<el-button type="primary" size="mini" :disabled="isBtn" @click="adDialogVisible=true">添加属性</el-button>
					<!-- 静态参数表格 -->
					<el-table :data="onlyList" border stripe>
						<!-- 展开行 -->
						<el-table-column type="expand">
						
							<template slot-scope="scope">
								<!-- 循环渲染tag标签 -->
								<el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
								<!-- 输入的文本框 -->
								<el-input class="input-new-tag" 
								v-if="scope.row.inputVisible" 
								v-model="scope.row.inputValue" 
								ref="saveTagInput" size="small"
								@keyup.enter.native="handleInputConfirm(scope.row)" 
								@blur="handleInputConfirm(scope.row)">
								</el-input>
								<!-- <span>{{scope.row}}</span> -->
								<!-- 添加按钮 -->
								<el-button v-else class="button-new-tag" 
								size="small" @click="showInput(scope.row)">+ New Tag</el-button>
								<pre>
									{{scope.row}}
								</pre>
							</template>
						</el-table-column>
						<el-table-column type="index"></el-table-column>
						<el-table-column label="属性名称" prop="attr_name"></el-table-column>
						<el-table-column label="操作">
							<template v-slot="scope">
								<el-button type="success" icon="el-icon-edit" size="mini" @click="showClick(scope.row.attr_id)">编辑</el-button>
								<el-button type="info" icon="el-icon-delete" size="mini" @click="removeBtn(scope.row.attr_id)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			</el-tabs>
		</el-card>
		<!-- 添加参数对话框 -->
		<el-dialog :title="'添加' + titleText" :visible.sync="adDialogVisible" width="50%" @close="addDialog">

			<el-form :model="addForm" :rules="addrules" ref="addruleForm" label-width="100px" class="demo-ruleForm">
				<el-form-item :label="titleText" prop="attr_name">
					<el-input v-model="addForm.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="adDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addDialogVisible">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 添加修改对话框 -->
		<el-dialog :title="'修改' + titleText" :visible.sync="editialogVisible" width="50%" @close="editDialog">
			<el-form :model="editForm" :rules="editrules" ref="editruleForm" label-width="100px" class="demo-ruleForm">
				<el-form-item :label="titleText" prop="attr_name">
					<el-input v-model="editForm.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editFrom">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				cateList: [],
				cateProps: {
					value: 'cat_id',
					label: 'cat_name',
					children: 'children'
				},

				value: [],
				// 被激活的页签
				activeName: 'many',

				manyList: [],

				onlyList: [],
				// 控制添加对话框显隐
				adDialogVisible: false,

				// 添加参数表单数据对象
				addForm: {
					attr_name: '',
				},

				addrules: {
					attr_name: [{
						required: true,
						message: '请输入参数名称',
						trigger: 'blur'
					}]
				},
				// 控制修改参数对话框显隐
				editialogVisible: false,
				// 修改表单的数据对象
				editForm: {},
				// 修改表单的验证规则对象
				editrules: {
					attr_name: [{
						required: true,
						message: '请输入参数名称',
						trigger: 'blur'
					}]
				},
				// // 控制文本框与按钮切换显示
				// inputVisible: false,
				// // 文本框输入的内容
				// inputValue: ''
			}
		},
		computed: {
			isBtn() {
				if (this.value.length !== 3) {
					return this.value.length === 0 ? true : false

				}
			},
			// 分类ID
			cateId() {
				if (this.value.length === 3) {
					return this.value.length[2]
					// return this.value.length === 3 ? this.value. [this.value.length - 1] : ''
					// return this.value.length === 3 ? this.value. [this.value.length - 1] : ''
				}
			},

			titleText() {
				if (this.activeName == 'many') {
					return '动态'
				}
				return '静态'
			}
		},
		created() {
			this.getCateList()
		},


		methods: {

			// 获取商品分类列表
			async getCateList() {
				const {
					data: res
				} = await this.$http.get('/categories1')
				if (res.meta.status !== 200) {
					return this.$message.error('获取商品列表失败')
				}
				this.cateList = res.data
				console.log(this.cateList)
			},

			// 级联选择器发生变化,出发这个函数
			handleChange() {
				this.getParams()
			},

			// tab页签点击处理函数
			handleClick() {
				console.log(this.activeName)
				this.getParams()
			},

			// 获取参数列表数据
			async getParams() {
				if (this.value.length !== 3) {
					this.value = []
					this.manyList = []
					this.onlyList = []
					return
				}
				console.log(this.value)
				const {
					data: res
				} = await this.$http.get(`/categories/${this.cateId}/attributes`, {
					params: {
						sel: this.activeName
					}
				})
				if (res.meta.status !== 200) {
					return this.$message.error('获取失败')
				}

				res.data.forEach(item => {
					item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [],
					// 控制文本框显示与隐藏
					item.inputVisible = false
					item.inputValue = ''
				})
				console.log(res.data)
				if (this.activeName === 'many') {
					this.manyList = res.data
				} else {
					this.onlyList = res.data
				}

			},
			addDialog() {
				this.$refs.addruleForm.resetFields()
			},
			addDialogVisible() {
				this.$refs.addruleForm.validate(async valid => {
					if (!valid) return
					const {
						data: res
					} = await this.$http.get(`/categories/${this.cateId}/attributes2`, {
						attr_name: this.addForm.attr_name,
						attr_sel: this.activeName
					})
					if (res.meta.status !== 201) {
						return this.$message.error('添加参数失败')
					}

					this.$message.success('添加参数成功')
					this.getCateList()
					this.adDialogVisible = false
				})
			},
			// 点击按钮展示编辑对话框
			async showClick(attr_id) {
				const {
					data: res
				} = await this.$http.
				get(`/categories/${this.cateId}/attributes/${attr_id}`, {
					params: {
						attr_sel: this.activeName
					}
				})
				if (res.meta.status !== 200) {
					return this.$message.error('修改失败')
				}
				this.editForm = res.data
				// this.$message.success('修改成功')								
				this.editialogVisible = true
			},
			// 重置修改表单
			editDialog() {
				this.$refs.editruleForm.resetFields()
			},
			//点击修改参数
			editFrom() {
				this.$refs.editruleForm.validate(async valid => {
					if (!valid) return
					const {
						data: res
					} = await this.$http.
					put(`/categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
						attr_name: this.editForm.attr_name,
						attr_sel: this.activeName
					})
					if (res.meta.status !== 200) {
						return this.$message.error('修改失败')
					}
					this.$message.success('修改成功')
					this.getCateList()
					this.editialogVisible = false
				})
			},
			async removeBtn(attr_id) {
				const resconfirm = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)
				if (resconfirm !== 'confirm') {
					return this.$message.info('取消删除')
				}
				const {
					data: res
				} = await this.$http.delete(`/categories/${this.cateId}/attributes/${attr_id}`)
				if (res.meta.status !== 200) {
					return this.$message.error('删除失败')
				}
				this.$message.success('删除成功')
				this.getCateList()
			},
			// 文本框失去焦点或按下触发
			handleInputConfirm(row) {
        
			  if(row.inputValue.trim().length === 0) {
					row.inputValue = ''
					row.inputVisible = false
					return
				}
				// console.log(row.inputValue,row.inputVisible)
				row.attr_vals.push(row.inputValue.trim())
				row.inputValue = ''
				row.inputVisible = false 
				this.saveAttr(row)
				
			},
				// 发起请求保存操作
			async saveAttr(row) {
				const {data:res} = await this.$http.put
				(`/categories/${this.cateId}/attributes/${row.attr_id}`,
				{attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ')})
				if(res.meta.status !== 200) {
					return this.$message.error('添加参数失败')
				} 
				this.$message.success('添加参数成功')
			},
			// 点击按钮展示文本输入框
			showInput(row) {
				row.inputVisible = true
				// 让文本框自动获取焦点
				  this.$nextTick(_ => {
				    this.$refs.saveTagInput.$refs.input.focus();
				});
			},
			// 删除tag标签，保存数据
			handleClose(i, row) {
				row.attr_vals.splice(i,1)
				this.saveAttr(row)
			}
		}

	}
</script>

<style lang="less" scoped>
	.cat_opt {
		margin: 15px 0;
	}

	.el-tag {
		margin: 10px;
	}
	.input-new-tag {
		width: 120px;
	}
</style>
